﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Shl01.Models;

namespace Shl01.Dal
{
    [Serializable]
    public class Fang
    {
        /// <summary>
        /// 返回所有数据库
        /// </summary>
        /// <param name="con">数据库模型</param>
        /// <returns>查询到的所有数据库表</returns>
        /// <exception cref="有异常就抛出"></exception>
        public DataTable GetAllDatabase(Conn con)
        {
            string ConnStr = "";
            if (con.Type == 0)
            {
                ConnStr = string.Format("serVer = {0}; database = master;uid = {1};pwd = {2}", con.Fuwu, con.Id, con.Pwd);
            }
            else
            {
                ConnStr = string.Format("Data Source={0};Initial Catalog=master;Integrated Security=True", con.Fuwu);
            }
            using (SqlConnection conn = new SqlConnection(ConnStr))
            {
                string sql = "sp_databases";
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    adapter.Fill(ds);
                    return ds.Tables[0];
                }
            }
        }
        /// <summary>
        /// 返回当前数据库的所有表
        /// </summary>
        /// <param name="con">数据库模型</param>
        /// <returns>所有表</returns>
        /// <exception cref="有异常则抛出"></exception>
        public DataTable GetAllTables(Conn con,string database)
        {
            string ConnStr = "";
            if (con.Type == 0)
            {
                ConnStr = string.Format("serVer = {0}; database = {3};uid = {1};pwd = {2}", con.Fuwu, con.Id, con.Pwd,database);
            }
            else
            {
                ConnStr = string.Format("Data Source={0};Initial Catalog={0};Integrated Security=True", con.Fuwu,database);
            }
            using (SqlConnection conn = new SqlConnection(ConnStr))
            {
                string sql = @"SELECT * FROM INFORMATION_SCHEMA.TABLES where table_type = 'BASE TABLE' ORDER BY TABLE_NAME";
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    adapter.Fill(ds);
                    return ds.Tables[0];
                }
            }
        }
    }
}
